package com.oepm.web.controller;

import com.oepm.biz.ResultBiz;
import com.oepm.common.entity.Meta;
import com.oepm.common.entity.Result;
import com.oepm.common.utils.JWTUtil;
import com.oepm.dao.entity.QueryInfo;
import com.oepm.dao.entity.ResultPo;
import com.oepm.vo.DataVo;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin//解决跨域
@RestController
@Api(tags = "成果管理")
public class ResultController {

    @Autowired
    private ResultBiz resultBiz;
    @Value(value = "${upload_path}")
    private String upload_path;//资源文件绝对地址目录

    //文件上传
    @RequestMapping("/resultUpload/upload")
    @RequiresRoles(value = {"5"})
    public Result resultUpload(@RequestParam(value = "file", required = false) MultipartFile file,
                               @RequestParam("pid") String pid,
                               HttpServletRequest request) throws IOException {

        //判断文件是否为空
        if (file.isEmpty()) {
            return new Result(Meta.FAIL);
        }


        //判断学生是否有权利修改
        String authorization = request.getHeader("Authorization");
        String userId = JWTUtil.getUserId(authorization);

        String Id = resultBiz.queryUserIdByPid(pid);
        if(!Id.equals(userId)){
            return new Result(Meta.FAIL);
        }

        //上传路径保存设置
//        String path = request.getServletContext().getRealPath("/upload/"+pid);
        File realPath = new File(upload_path+"/uploadResult/"+pid);
        if (!realPath.exists()){
            realPath.mkdirs();
        }
        //每次上传删除上次上传文件
        File[] files = realPath.listFiles();
        for (File file1:files){
            file1.delete();
        }
        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        //重新定义文件名避免重复
        String filename = file.getOriginalFilename();
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath +"/"+ filename));

        //保存到数据库
        String address = "/"+pid+"/"+filename;
        ResultPo resultPo = new ResultPo(pid,filename,address);
        int flag = resultBiz.updateResult(resultPo);
        if(flag==1){
            return new Result(Meta.SUCCESS);
        }


        return new Result(Meta.FAIL);
    }


    //成果上传-查 自己所有项目成果
    @GetMapping("/resultUpload/select")
    public Result selectResults(HttpServletRequest request,
                                QueryInfo queryInfo){
        String authorization = request.getHeader("Authorization");
        String userId = JWTUtil.getUserId(authorization);
        DataVo<ResultPo> resVo = resultBiz.selectResultsStu(userId, queryInfo);
        Result result = new Result(Meta.SUCCESS);
        result.setData(resVo);
        return result;

    }

    // 成果列表-单个查 按项目名
    @GetMapping("/result/selectId/{pname}")
    public Result selectResultAll(@PathVariable String pname){
        List<ResultPo> resultPos = resultBiz.selectResults(pname);
        Result result = new Result(Meta.SUCCESS);
        result.setData(resultPos);
        return result;
    }

    // 成果列表-查所有 文件下载 -成果
    @GetMapping("/result/select")
    public Result selectResultAlls(QueryInfo queryInfo){
        DataVo<ResultPo> resultPoDataVo = resultBiz.selectResultAll(queryInfo);
        Result result = new Result(Meta.SUCCESS);
        result.setData(resultPoDataVo);
        return result;
    }

    //文件下载
    @RequestMapping(value="/result/download/{pid}")
    public Result downloads(HttpServletResponse response ,
                            @PathVariable("pid") String pid,
                            HttpServletRequest request) throws Exception{
        //要下载的图片地址
        ResultPo resultPo = resultBiz.queryAddressByPid(pid);
        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据

        //跨域设置
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "*");


        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(resultPo.getResults(), "UTF-8"));

        File file = new File(upload_path+"/uploadResult/"+resultPo.getResult_address());
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();

        return new Result(Meta.SUCCESS);
    }
}
